/************************************************************************
 * The code is owned by mainframer.cn and Shang Tao
 * Without aproval of mainframer.cn and Shang Tao, removing the copyright
 * infomation is regarded as invassion of proprietary copyright
 ***********************************************************************/
package com.mr.qa.action;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.io.Util;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.actions.DispatchAction;
import org.apache.struts.upload.FormFile;
import org.hibernate.Transaction;

import com.mr.qa.GlobalConfigs;
import com.mr.qa.UserSession;
import com.mr.qa.UserSessionUtil;
import com.mr.qa.action.check.DailyAddSharedFileCheck;
import com.mr.qa.action.check.DailyCheck;
import com.mr.qa.action.check.DailyDownloadSharedFileCheck;
import com.mr.qa.bo.SharedFile;
import com.mr.qa.bo.SharedFileCategory;
import com.mr.qa.bo.User;
import com.mr.qa.dao.impl.SharedFileCategoryDAO;
import com.mr.qa.dao.impl.SharedFileDAO;
import com.mr.qa.dao.impl.UserDAO;
import com.mr.qa.dao.impl.UserScoreHistoryConstants;
import com.mr.qa.exception.QaException;
import com.mr.qa.form.ShareFileForm;
import com.mr.qa.util.HibernateSessionFactory;


public class SharedFileAction extends DispatchAction 
{
    private static final Log log = LogFactory.getLog(SharedFileAction.class);
 
    private final static String PREADD_FORWARD_NAME = "add-failure";
    private final static String MODIFY_FAILURE_FORWARD_NAME = "modify-failure";
    
    public final static int nameMaxLength = 40;
    
    public static String fileSeparator;
    static
    {
        String fileSeparator = File.separator;
        if(fileSeparator.equals("\\"))
        {
            fileSeparator = "/";
        }
        SharedFileAction.fileSeparator = fileSeparator;
    }
    
    private ActionForward checkIfUserLogined(ActionMapping mapping,HttpServletRequest request,ActionMessages errors)
    {
        UserSession us = UserSessionUtil.getUserSession(request);
        ActionForward af = null;
        if(us == null)
        {
            errors.add("relogin", new ActionMessage("login.required"));
            saveErrors(request, errors);
            af = mapping.findForward("relogin"); 
        }
        return af;
    }

    private ActionForward checkIfUserIsAdmin(ActionMapping mapping,HttpServletRequest request,ActionMessages errors)
    {
        UserSession us = UserSessionUtil.getUserSession(request);
        ActionForward af = null;
        if(us == null)
        {
            errors.add("relogin", new ActionMessage("login.required"));
            saveErrors(request, errors);
            af = mapping.findForward("relogin"); 
        }
        else
        {
            if(!us.getType().equals("1"))
            {
                errors.add("noright", new ActionMessage("user.noright"));
                saveErrors(request, errors);
                af = mapping.findForward("relogin");
            }
        }
        return af;
    }
    
    public ActionForward search(ActionMapping mapping, ActionForm form,
                HttpServletRequest request, HttpServletResponse response) 
                throws Exception
    {
        ActionForward af = null;
        ShareFileForm shareFileForm = (ShareFileForm)form;        
        Integer page = shareFileForm.getPage();
        if(page == null || page == 0)
        {
            page = 1;
        }
        int pageSize = shareFileForm.getPageSize();
        if(pageSize == 0)
        {
            pageSize = GlobalConfigs.SIZE_SHAREDFILE_LIST;
        }
        String searchText = shareFileForm.getName();
        int resultSize = countSearch(searchText);
        List list = search(page, pageSize,searchText);
        request.setAttribute("sfs",list);
        saveInRequest(request,resultSize,list.size(),pageSize);//2008.9.10
        af = mapping.findForward(getStrutsMappingParamterValue(mapping,request));
        return af;
    }
    
    /**
     * add a shared file
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward add(ActionMapping mapping, ActionForm form,
                HttpServletRequest request, HttpServletResponse response) 
                throws Exception
    {
        ActionForward af = null;
        ActionMessages errors = new ActionMessages();
        UserSession us = UserSessionUtil.getUserSession(request);
        if(!this.isTokenValid(request,true))
        {
            errors.add("", new ActionMessage("duplicatesubmission"));
            saveErrors(request, errors);
            saveToken(request); 
            af = mapping.findForward(PREADD_FORWARD_NAME);
            return af;
        }
        else
        {
            resetToken(request); 
        }
        af = checkIfUserLogined(mapping,request,errors);
        if(af != null)return af;
        ShareFileForm shareFileForm = (ShareFileForm)form;
        String name = shareFileForm.getName();
        FormFile file = shareFileForm.getFile();
        Integer catId = shareFileForm.getCatId();
        if(file == null || file.getFileSize() == 0)
        {
            errors.add("", new ActionMessage("sharedfile.file.required"));
        }
        else
        {
        	if(!us.isActive()){
        		errors.add("addquestion-limit", new ActionMessage("user.inactive", ""));
        	}
        	if(!us.getType().equals("1")){
        		int fileSize = file.getFileSize();
        		if(fileSize > GlobalConfigs.SIZE_SHAREDFILE)
        		{
        			errors.add("", new ActionMessage("sharedfile.oversize","5"));
        		}
        	}
        }
        
        if(name == null)
        {
            errors.add("", new ActionMessage("sharedfile.name.required"));
        }
        else
        {
            if(name.length() > nameMaxLength)
            {
                errors.add("", new ActionMessage("sharedfile.name.overlength",""+nameMaxLength));
            }
        }
        if(catId == null)
        {
            errors.add("", new ActionMessage("sharedfile.catid.required"));
        }
        
        String vc = shareFileForm.getVc();
        if(vc == null)vc = "";
        String vcinSession = UserSessionUtil.getVerificationCodes(request);
        if(vc.length() == 0)
        {
            errors.add("vc", new ActionMessage("verificationcode.required"));
        }
        else if(!vc.equals(vcinSession))
        {
            errors.add("vc", new ActionMessage("verificationcode.error"));
        }
        if(errors.size() > 0)
        {
            saveErrors(request, errors);
            saveErrors(request.getSession(), errors);
            af = mapping.findForward(PREADD_FORWARD_NAME);
            return af;
        }
        int newSharedFileId = add(shareFileForm,us.getUserId(),errors);
        if(newSharedFileId == 0)
        {
            saveErrors(request, errors);
            af = mapping.findForward(PREADD_FORWARD_NAME);
            return af;
        }
        if(errors.size() > 0)
        {
            saveErrors(request, errors);
            saveErrors(request.getSession(), errors);
        }
        //add file
        af = mapping.findForward(getStrutsMappingParamterValue(mapping,request));
        String path = af.getPath();
        path = path.replace("?id",newSharedFileId+"");
        af = new ActionForward(path);
        af.setRedirect(true);
        return af;
    } 

    /**
     * modify a shared file, if file is null, means the user did not want to change 
     * the file
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward modify(ActionMapping mapping, ActionForm form,
                HttpServletRequest request, HttpServletResponse response) 
                throws Exception
    {
        ActionForward af = null;
        ActionMessages errors = new ActionMessages();       
        UserSession us = UserSessionUtil.getUserSession(request);
        af = checkIfUserLogined(mapping,request,errors);
        if(af != null)return af;
        ShareFileForm shareFileForm = (ShareFileForm)form;
        FormFile file = shareFileForm.getFile();
        if(file != null && file.getFileSize() > 0)
        {
        	if(!us.getType().equals("1")){
        		int fileSize = file.getFileSize();
        		if(fileSize > GlobalConfigs.SIZE_SHAREDFILE)
        		{
        			errors.add("", new ActionMessage("sharedfile.oversize","5"));
        		}
        	}
        }
        String name = shareFileForm.getName();
        if(name == null)
        {
            errors.add("", new ActionMessage("sharedfile.name.required"));
        }
        else if(name.length() > nameMaxLength)
        {
            errors.add("", new ActionMessage("sharedfile.name.overlength",""+nameMaxLength));
        }
        if(errors.size() > 0)
        {
            saveErrors(request, errors);
            String path = mapping.findForward(MODIFY_FAILURE_FORWARD_NAME).getPath();
            path = path.replace("?id",""+shareFileForm.getId());
            af = new ActionForward(path);
            af.setRedirect(true);
            return af;
        }
        modify(shareFileForm,us.getUserId(),errors);
        if(errors.size() > 0)
        {
            saveErrors(request, errors);
            saveErrors(request.getSession(), errors);
        }
        //add file
        af = mapping.findForward(getStrutsMappingParamterValue(mapping,request));
        String path = af.getPath();
        path = path.replace("?id",""+shareFileForm.getId());
        af = new ActionForward(path);
        af.setRedirect(true);
        return af;
    } 


    /**
     * change category
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward changecat(ActionMapping mapping, ActionForm form,
                HttpServletRequest request, HttpServletResponse response) 
                throws Exception
    {
        ActionForward af = null;
        ActionMessages errors = new ActionMessages();        
        af = checkIfUserIsAdmin(mapping,request,errors);
        if(af != null)return af;
        ShareFileForm shareFileForm = (ShareFileForm)form;
        //
        if(errors.size() > 0)
        {
            saveErrors(request, errors);
            saveErrors(request.getSession(), errors);
        }
        //change cat
        changeCat(shareFileForm.getId(),shareFileForm.getCatId(),errors);
        af = mapping.findForward(getStrutsMappingParamterValue(mapping,request));
        String path = af.getPath();
        path = path.replace("?id",""+shareFileForm.getId());
        af = new ActionForward(path);
        af.setRedirect(true);
        return af;
    } 

    /**
     * recommend or unrecommend
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward recommend(ActionMapping mapping, ActionForm form,
                HttpServletRequest request, HttpServletResponse response) 
                throws Exception
    {
        ActionForward af = null;
        ActionMessages errors = new ActionMessages();        
        af = checkIfUserIsAdmin(mapping,request,errors);
        if(af != null)return af;
        ShareFileForm shareFileForm = (ShareFileForm)form;
        //
        if(errors.size() > 0)
        {
            saveErrors(request, errors);
            saveErrors(request.getSession(), errors);
        }
        recommend(shareFileForm.getId(),errors);
        af = mapping.findForward(getStrutsMappingParamterValue(mapping,request));
        String path = af.getPath();
        path = path.replace("?id",""+shareFileForm.getId());
        af = new ActionForward(path);
        af.setRedirect(true);
        return af;
    } 


    /**
     * hide or open
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward hide(ActionMapping mapping, ActionForm form,
                HttpServletRequest request, HttpServletResponse response) 
                throws Exception
    {
        ActionForward af = null;
        ActionMessages errors = new ActionMessages();        
        af = checkIfUserIsAdmin(mapping,request,errors);
        if(af != null)return af;
        ShareFileForm shareFileForm = (ShareFileForm)form;
        //
        if(errors.size() > 0)
        {
            saveErrors(request, errors);
            saveErrors(request.getSession(), errors);
        }
        hideOrOpen(shareFileForm.getId(),errors);
        af = mapping.findForward(getStrutsMappingParamterValue(mapping,request));
        String path = af.getPath();
        path = path.replace("?id",""+shareFileForm.getId());
        af = new ActionForward(path);
        af.setRedirect(true);
        return af;
    } 

    public ActionForward confirmdelete(ActionMapping mapping, ActionForm form,
                HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        ActionForward af = null;
        ShareFileForm shareFileForm = (ShareFileForm)form;
        int sharedFileId = shareFileForm.getId();
        request.setAttribute("sharedfile",get(sharedFileId));
        af = mapping.findForward(getStrutsMappingParamterValue(mapping,request));
        //saveUserMessageSizeAndUpdateUserScoreInSession(request);
        return af;
    }    

    /**
     * 1.the user must logined and author
     * 2.the user is admin
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward delete(ActionMapping mapping, ActionForm form,
                HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        ActionForward af = null;
        ActionMessages errors = new ActionMessages();        
        af = checkIfUserLogined(mapping,request,errors);
        if(af != null)return af;
        ShareFileForm shareFileForm = (ShareFileForm)form;
        String vcInSession = UserSessionUtil.getVerificationCodes(request);
        String vcInForm = shareFileForm.getVc();
        if(vcInForm == null || vcInForm.length() == 0)
        {
            errors.add("vc", new ActionMessage("verificationcode.required"));
        }
        else if(!vcInForm.equals(vcInSession))
        {
            errors.add("vc", new ActionMessage("verificationcode.error"));
        }
        Integer id = shareFileForm.getId();       
        if(errors.size() > 0)
        {
            saveErrors(request,errors);
            String path = mapping.findForward("confirmdelete1").getPath();
            path += "&id="+id;
            ActionForward af1 = new ActionForward(path);
            return af1;
        }
        UserSession us = UserSessionUtil.getUserSession(request);
        int catId = delete(id,us.getUserId(),us.getType(),errors);
        if(catId >= 0)
        {
            af = mapping.findForward(getStrutsMappingParamterValue(mapping,request));
            String path = af.getPath();
            path = path+"&catId="+catId;
            af = new ActionForward(path);
            af.setRedirect(true);
        }
        else
        {
            af = mapping.findForward("delete1");
            String path = af.getPath();
            path = path+"&id="+id;
            af = new ActionForward(path);
            af.setRedirect(true);
        }
        if(errors.size() > 0)
        {
            saveErrors(request.getSession(), errors);
        }
        return af;
    }


    public ActionForward recommendedlist(ActionMapping mapping, ActionForm form,
                HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        ActionForward af = null;
        ShareFileForm shareFileForm = (ShareFileForm)form;        
        Integer page = shareFileForm.getPage();
        if(page == null || page == 0)
        {
            page = 1;
        }
        int pageSize = shareFileForm.getPageSize();
        if(pageSize == 0)
        {
            pageSize = GlobalConfigs.SIZE_SHAREDFILE_LIST;
        }
        Integer catId = shareFileForm.getCatId();        
        int resultSize = countRecommendedSharedFile(catId);
        List list = recommendedList(page, pageSize,catId,request);
        request.setAttribute("sfs",list);
        saveInRequest(request,resultSize,list.size(),pageSize);//2008.9.10
        af = mapping.findForward(getStrutsMappingParamterValue(mapping,request));
       // saveUserMessageSizeAndUpdateUserScoreInSession(request);
        return af;
    }
    
    
    public ActionForward list(ActionMapping mapping, ActionForm form,
                HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        ActionForward af = null;
        ShareFileForm shareFileForm = (ShareFileForm)form;        
        Integer page = shareFileForm.getPage();
        if(page == null || page == 0)
        {
            page = 1;
        }
        int pageSize = shareFileForm.getPageSize();
        if(pageSize == 0)
        {
            pageSize = GlobalConfigs.SIZE_SHAREDFILE_LIST;
        }
        Integer catId = shareFileForm.getCatId();        
        int resultSize = countSharedFile(catId);
        List list = list(page, pageSize,catId,request);
        request.setAttribute("sfs",list);
        saveInRequest(request,resultSize,list.size(),pageSize);//2008.9.10
        af = mapping.findForward(getStrutsMappingParamterValue(mapping,request));
        return af;
    }
    
    private void saveInRequest(HttpServletRequest request,int totalSize,int listSize,int sizePerPage)
    {
        request.setAttribute("resultSize",totalSize);
        request.setAttribute("filesSize",listSize);
        request.setAttribute("filesSizePerPage",sizePerPage);
        request.setAttribute("pageSize",sizePerPage);
    }
    
    
    public ActionForward preadd(ActionMapping mapping, ActionForm form,
                HttpServletRequest request, HttpServletResponse response) throws Exception
    {
    	
        ActionForward af = null;
        ActionMessages errors = new ActionMessages();        
        af = checkIfUserLogined(mapping,request,errors);
        checkCanAdd(mapping,request,errors);
        if(af != null)return af;
        saveErrors(request, errors);
        this.saveToken(request);
        af = mapping.findForward(getStrutsMappingParamterValue(mapping,request));
        
       // saveUserMessageSizeAndUpdateUserScoreInSession(request);
        return af;
    }
    
    public ActionForward premodify(ActionMapping mapping, ActionForm form,
                HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        ActionForward af = null;
        ShareFileForm shareFileForm = (ShareFileForm)form;
        int sharedFileId = shareFileForm.getId();
        request.setAttribute("sharedfile",get(sharedFileId));
        af = mapping.findForward(getStrutsMappingParamterValue(mapping,request));
       // saveUserMessageSizeAndUpdateUserScoreInSession(request);
        return af;
    }

    //viewCount increase

    public ActionForward view(ActionMapping mapping, ActionForm form,
                HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        ActionForward af = null;
        ShareFileForm shareFileForm = (ShareFileForm)form;
        int sharedFileId = shareFileForm.getId();
        request.setAttribute("sharedfile",view(sharedFileId));
        
        checkDownload(request);
        
        af = mapping.findForward(getStrutsMappingParamterValue(mapping,request));
       // saveUserMessageSizeAndUpdateUserScoreInSession(request);
        return af;
    }

    public ActionForward get(ActionMapping mapping, ActionForm form,
                HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        ActionForward af = null;
        ShareFileForm shareFileForm = (ShareFileForm)form;
        int sharedFileId = shareFileForm.getId();
        request.setAttribute("sharedfile",get(sharedFileId));
        
        checkDownload(request);
        
        af = mapping.findForward(getStrutsMappingParamterValue(mapping,request));
        //save user message size in session and update user score
       // saveUserMessageSizeAndUpdateUserScoreInSession(request);
        return af;
    }

    /**
     * return his shared files, suports pagination
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws java.lang.Exception
     */
    public ActionForward hislist(ActionMapping mapping, ActionForm form,
                HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        ActionForward af = null;
        ShareFileForm shareFileForm = (ShareFileForm)form;
        //url:user.mrqa?id=xxx
        Integer userId = shareFileForm.getId();
        int pageNo = shareFileForm.getPage();
        int pageSize = shareFileForm.getPageSize();
        if(pageNo == 0)pageNo = 1;
        if(pageSize == 0)pageSize = 25;
        //System.out.println("pageNo="+pageNo+",pageSize="+pageSize+",userId="+userId);
        List list = hislist(pageNo,pageSize,new Integer(userId));
        //System.out.println("list.size="+list.size());
        int resultSize = countHislist(new Integer(userId));
        //System.out.println("resultSize="+resultSize);
        request.setAttribute("sfs",list);
        saveInRequest(request,resultSize,list.size(),pageSize);//2008.9.10
        String action = getStrutsMappingParamterValue(mapping,request);
        //System.out.println("action="+action);
        //System.out.println("mapping="+mapping.findForwards());
        af = mapping.findForward(action);
        //System.out.println("af="+af);
        //save user message size in session and update user score
       // saveUserMessageSizeAndUpdateUserScoreInSession(request);
        return af;
    }

    /*
     *Below are private methods
     */
    private List hislist(int page,int pageSize,Integer userId) throws QaException
    {
        Transaction tx = null;
        try
        {
            SharedFileDAO sharedFileDAO = new SharedFileDAO();
            sharedFileDAO.setPage(page, pageSize);
            tx = HibernateSessionFactory.getSession().beginTransaction();
            List list = null;
            list = sharedFileDAO.hislist(userId);
            tx.commit();
            return list;
        }
        catch(Exception e)
        {
            if(tx != null)tx.rollback();
            throw new QaException(e);
        }
        finally
        {
            HibernateSessionFactory.closeSession();
        }
    }

    private int countHislist(Integer userId) throws QaException
    {
        Transaction tx = null;
        int count = 0;
        try
        {
            SharedFileDAO sharedFileDAO = new SharedFileDAO();
            tx = HibernateSessionFactory.getSession().beginTransaction();
            count = sharedFileDAO.countHislist(userId);
            tx.commit();
        }
        catch(Exception e)
        {
            if(tx != null)tx.rollback();
            throw new QaException(e);
        }
        finally
        {
            HibernateSessionFactory.closeSession();
        }
        return count;
    }
    /**
     * return my shared files, suports pagination
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws java.lang.Exception
     */
    public ActionForward mylist(ActionMapping mapping, ActionForm form,
                HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        ActionForward af = null;
        UserSession us = UserSessionUtil.getUserSession(request);
        if(us == null)throw new SecurityException("Please Login to See My Shared Files");
        ShareFileForm shareFileForm = (ShareFileForm)form;
        int pageNo = shareFileForm.getPage();
        int pageSize = shareFileForm.getPageSize();
        if(pageNo == 0)pageNo = 1;
        if(pageSize == 0)pageSize = 25;
        List list = mylist(pageNo,pageSize,new Integer(us.getUserId()));
        int resultSize = countMylist(new Integer(us.getUserId()));
        request.setAttribute("sfs",list);
        saveInRequest(request,resultSize,list.size(),pageSize);//2008.9.10
        af = mapping.findForward(getStrutsMappingParamterValue(mapping,request));
        //save user message size in session and update user score
       // saveUserMessageSizeAndUpdateUserScoreInSession(request);
        return af;
    }

    /*
     *Below are private methods
     */
    private List mylist(int page,int pageSize,Integer userId) throws QaException
    {
        Transaction tx = null;
        try
        {
            SharedFileDAO sharedFileDAO = new SharedFileDAO();
            sharedFileDAO.setPage(page, pageSize);
            tx = HibernateSessionFactory.getSession().beginTransaction();
            List list = null;
            list = sharedFileDAO.mylist(userId);
            tx.commit();
            return list;
        }
        catch(Exception e)
        {
            if(tx != null)tx.rollback();
            throw new QaException(e);
        }
        finally
        {
            HibernateSessionFactory.closeSession();
        }
    }

    private int countMylist(Integer userId) throws QaException
    {
        Transaction tx = null;
        int count = 0;
        try
        {
            SharedFileDAO sharedFileDAO = new SharedFileDAO();
            tx = HibernateSessionFactory.getSession().beginTransaction();
            count = sharedFileDAO.countMylist(userId);
            tx.commit();
        }
        catch(Exception e)
        {
            if(tx != null)tx.rollback();
            throw new QaException(e);
        }
        finally
        {
            HibernateSessionFactory.closeSession();
        }
        return count;
    }


    private String getStrutsMappingParamterValue(ActionMapping mapping,HttpServletRequest request)
    {
        return request.getParameter(mapping.getParameter());
    }
    
    private String getDateTimeString(int sharedFileId)
    {
        Date currentDate = new Date();
        SimpleDateFormat bartDateFormat = new SimpleDateFormat("yyyy-MM-dd-hh-ss-mm"); 
        return bartDateFormat.format(currentDate)+"_"+sharedFileId+"_";
    }
    
    //   /userid/yyyy-mm-dd-hh-ss-mm/
    private String makePhisicalFilePath(int userId,int sharedFileId)
    {
        String fileSeperator = fileSeparator;
        if(fileSeperator.equals("\\"))
        {
            fileSeperator = "/";
        }
        String phisicalFilePath = fileSeperator+userId+fileSeperator+getDateTimeString(sharedFileId)+fileSeparator;
        return phisicalFilePath;
    }
    
    /*
     * new add 2008-4-19
     * yyyy-mm-dd
     */
    private int addBack(ShareFileForm shareFileForm, Integer userId,ActionMessages errors) throws QaException
    {
        Transaction tx = null;
        int newSharedFileId = 0;
        try
        {
            FormFile file = shareFileForm.getFile();
            String fName = file.getFileName();
            String name = shareFileForm.getName();
            //log.info("shared file name:"+name+"whose length is :"+name.length());
            SharedFileDAO sharedFileDAO = new SharedFileDAO();
            UserDAO userDAO = new UserDAO();
            SharedFileCategoryDAO sharedFileCategoryDAO = new SharedFileCategoryDAO();
            tx = HibernateSessionFactory.getSession().beginTransaction();
            User user = userDAO.findById(userId);
            SharedFileCategory sharedFileCategory = sharedFileCategoryDAO.findById(shareFileForm.getCatId());
            sharedFileCategory.setFileCount(sharedFileCategory.getFileCount()+1);
            Date date = new Date();
            SharedFile sharedFile = new SharedFile();
            String ext = fName.substring(fName.lastIndexOf(".")+1);
            sharedFile.setName(name);
            sharedFile.setSize(file.getFileSize());
            sharedFile.setPostDate(date);
            sharedFile.setChangeDate(date);
            sharedFile.setFileType(ext);
            sharedFile.setDescription(shareFileForm.getDescription());
            sharedFile.setMrIaskUser(user);
            sharedFile.setMrIaskSharedFileCategory(sharedFileCategory);
            sharedFile.setDownloadCount(0);
            sharedFile.setViewCount(0);
            sharedFile.setPath("");
            sharedFile.setIsRecommended(false);
            sharedFile.setState("0");
            sharedFileDAO.save(sharedFile);
            try
            {
                InputStream in = file.getInputStream();
                String sharedFileDirStr = GlobalConfigs.WEB_PHISICAL_ROOT_LOCATION+GlobalConfigs.SHAREDFILE_DIR;
                File sharedFileDir = new File(sharedFileDirStr);
                if(!sharedFileDir.exists())
                {
                    sharedFileDir.mkdir();
                }
                String userDirStr = sharedFileDirStr+fileSeparator+userId;
                File userDir = new File(userDirStr);
                if(!userDir.exists())
                {
                    userDir.mkdir();
                }
                String datetimeDirStr = userDirStr+fileSeparator+getDateTimeString(sharedFile.getId());
                File datetimeDir = new File(datetimeDirStr);
                if(!datetimeDir.exists())
                {
                    datetimeDir.mkdir();
                }
                
                /*
                
                String phisicalFileDirStr = GlobalConfigs.WEB_PHISICAL_ROOT_LOCATION
                +GlobalConfigs.SHAREDFILE_DIR+phisicalFilePath;
                System.out.println("phisicalFileDirStr="+phisicalFileDirStr);
                File phisicalFileDir = new File(phisicalFileDirStr);
                if(!phisicalFileDir.exists())
                {
                    phisicalFileDir.mkdir();
                    System.out.println("dir created");
                }*/
                
                
                
                
                String phisicalFile = datetimeDirStr+fileSeparator+name+"."+ext;
                
                //System.out.println("phisicalFilePath="+phisicalFile);
                //System.out.println("phisicalFilePath="+phisicalFile);
                OutputStream out = new FileOutputStream(phisicalFile);
                Util.copyStream(in, out);
                in.close();
                out.close();
            }
            catch(Exception e)
            {
                errors.add("",new ActionMessage("uploadfile.failure",fName));
                log.error("add share file into dir exception:"+e);
                throw e;
                //System.out.println("uploading file ex"+e);
            }
            
            
            /*
            if(fName.length() > 0)
            {
                InputStream in = file.getInputStream();
                Blob fileContent = Hibernate.createBlob(in);
                UploadedFile uf = new UploadedFile();
                uf.setId("sf"+sharedFile.getId());
                uf.setContent(fileContent);
                uf.setName(shareFileForm.getName());
                UploadedFileDAO ufDAO = new UploadedFileDAO();
                ufDAO.save(uf);
            }*/
            String phisicalFilePath = makePhisicalFilePath(userId,sharedFile.getId());
            //System.out.println(phisicalFilePath+name+"."+ext);
            sharedFile.setPath(phisicalFilePath+name+"."+ext);
            sharedFileDAO.modify(sharedFile);            
            sharedFileCategoryDAO.update(sharedFileCategory);
            //add 5 score to user
            sharedFileDAO.addScoreHistory(user,newSharedFileId,sharedFile.getName(),"uploadsharedfile","add sharedfile:"+name);
            tx.commit();
            newSharedFileId = sharedFile.getId();
        }
        catch(Exception e)
        {
            if(tx != null)tx.rollback();
            log.error("add share file object exception:"+e);
            //throw new QaException(e);
        }
        finally
        {
            HibernateSessionFactory.closeSession();  
        }
        return newSharedFileId;
    }        

    private int add(ShareFileForm shareFileForm, Integer userId,ActionMessages errors) throws QaException
    {
        Transaction tx = null;
        int newSharedFileId = 0;
        boolean needRollback = true;
        try
        {
            FormFile file = shareFileForm.getFile();
            //file name
            String fName = file.getFileName();
            //fName = fName.replaceAll(" ","");
            if(checkIfFileExist(fName))
            {
                errors.add("",new ActionMessage("sharedfile.exist",fName));
                needRollback = false;
                throw new QaException("File can not be overwrite");
            }
            
            //name only for text
            String name = shareFileForm.getName();
            //log.info("shared file name:"+name+"whose length is :"+name.length());
            
            SharedFileDAO sharedFileDAO = new SharedFileDAO();
            UserDAO userDAO = new UserDAO();
            SharedFileCategoryDAO sharedFileCategoryDAO = new SharedFileCategoryDAO();
            tx = HibernateSessionFactory.getSession().beginTransaction();
            User user = userDAO.findById(userId);
            SharedFileCategory sharedFileCategory = sharedFileCategoryDAO.findById(shareFileForm.getCatId());
            sharedFileCategory.setFileCount(sharedFileCategory.getFileCount()+1);
            
            //System.out.println("shared file name:"+name+"whose length is :"+name.length());
            Date date = new Date();
            SharedFile sharedFile = new SharedFile();
            String ext = fName.substring(fName.lastIndexOf(".")+1);
            sharedFile.setName(name);
            sharedFile.setSize(file.getFileSize());
            sharedFile.setPostDate(date);
            sharedFile.setChangeDate(date);
            sharedFile.setFileType(ext);
            sharedFile.setDescription(shareFileForm.getDescription());
            sharedFile.setMrIaskUser(user);
            sharedFile.setMrIaskSharedFileCategory(sharedFileCategory);
            sharedFile.setDownloadCount(0);
            sharedFile.setViewCount(0);
            sharedFile.setPath("");
            sharedFile.setIsRecommended(false);
            sharedFile.setState("0");
            sharedFileDAO.save(sharedFile);
            String filePath = "";
            try
            {
                InputStream in = file.getInputStream();
                String yearMonthDayPath = checkAndBuildYearMonthDayDir();// /yyyy/mm/dd
                String dirPath = getPhisicalSharedFileDir()+yearMonthDayPath;// /root/sharedfile/yyyy/mm/dd
                String phisicalFile = "";
                phisicalFile = dirPath+fileSeparator+fName;
                filePath = yearMonthDayPath+fileSeparator+fName;
                OutputStream out = new FileOutputStream(phisicalFile);
                Util.copyStream(in, out);
                in.close();
                out.close();
            }
            catch(Exception e)
            {
                errors.add("",new ActionMessage("uploadfile.failure",fName));
                log.error("add share file into dir exception:"+e);
                throw e;
            }
            sharedFile.setPath(filePath);
            sharedFileDAO.modify(sharedFile);            
            sharedFileCategoryDAO.update(sharedFileCategory);
            //add 5 score to user
            sharedFileDAO.addScoreHistory(user,newSharedFileId,sharedFile.getName(),"uploadsharedfile","add sharedfile:"+name);
            
            DailyCheck dailyCheck = new DailyAddSharedFileCheck();
            dailyCheck.update(userId);
            tx.commit();
            newSharedFileId = sharedFile.getId();
        }
        catch(QaException qe)
        {
            log.error("add share file object exception:"+qe);
        }
        catch(Exception e)
        {
            if(tx != null && needRollback)tx.rollback();
            log.error("add share file object exception:"+e);
            errors.add("", new ActionMessage("sharedfile.add.failure"));
        }
        finally
        {
            HibernateSessionFactory.closeSession();  
        }
        return newSharedFileId;
    }
    
    private boolean checkIfFileExist(String fileName)
    {
        Calendar calendar= Calendar.getInstance();
        String year = ""+calendar.get(Calendar.YEAR);
        String month = ""+(calendar.get(Calendar.MONTH)+1);
        String day = ""+calendar.get(Calendar.DATE);
        String yearDirPath = getPhisicalSharedFileDir()+fileSeparator+year
        +fileSeparator+month+fileSeparator+day;
        String phisicalFilePath = yearDirPath+fileSeparator+fileName;
        File phisicalFile = new File(phisicalFilePath);
        return phisicalFile.exists();
    }
    /**
     * 
     * @return the absolute path of shared file, e.g./root/sharedfile(unix)
     */
    private String getPhisicalSharedFileDir()
    {
        return GlobalConfigs.WEB_PHISICAL_ROOT_LOCATION+GlobalConfigs.SHAREDFILE_DIR;
    }
    /*
     * return built dirs
     */
    private String checkAndBuildYearMonthDayDir()
    {
    
        String sharedFileDirStr = getPhisicalSharedFileDir();
        Calendar calendar= Calendar.getInstance();
        String year = ""+calendar.get(Calendar.YEAR);
        String month = ""+(calendar.get(Calendar.MONTH)+1);
        String day = ""+calendar.get(Calendar.DATE);
        String yearDirPath = fileSeparator+year+fileSeparator+month+fileSeparator+day;
        String phisicalYearDirPath = sharedFileDirStr+yearDirPath;
        File phisicalYearPathDir = new File(phisicalYearDirPath);
        if(!phisicalYearPathDir.exists())
        {
            phisicalYearPathDir.mkdirs();
        }
        return yearDirPath;
    }


    private void changeCat(int sharedFileId,int newCatId,ActionMessages errors)
    {
        Transaction tx = null;
        try
        {
            SharedFileDAO sharedFileDAO = new SharedFileDAO();
            SharedFileCategoryDAO sharedFileCategoryDAO = new SharedFileCategoryDAO();
            tx = HibernateSessionFactory.getSession().beginTransaction();
            SharedFile sharedFile = sharedFileDAO.findById(sharedFileId);
            SharedFileCategory oldSharedFileCategory = sharedFile.getMrIaskSharedFileCategory();
            oldSharedFileCategory.setFileCount(oldSharedFileCategory.getFileCount()-1);
            SharedFileCategory sharedFileCategory = sharedFileCategoryDAO.findById(newCatId);
            sharedFileCategory.setFileCount(sharedFileCategory.getFileCount()+1);
            sharedFile.setMrIaskSharedFileCategory(sharedFileCategory);
            sharedFileCategoryDAO.update(oldSharedFileCategory);
            sharedFileCategoryDAO.update(sharedFileCategory);
            sharedFileDAO.modify(sharedFile);
            tx.commit();
        }
        catch(Exception e)
        {
            if(tx != null)tx.rollback();
            //throw new QaException(e);
        }
        finally
        {
            HibernateSessionFactory.closeSession();  
        }
    }
    /**
     * if share file is recommened, set to unrecommened
     * if share file is unrecommended, set to recommended
     * @param sharedFileId
     * @param errors
     */
    private void recommend(int sharedFileId,ActionMessages errors)
    {
        Transaction tx = null;
        try
        {
            SharedFileDAO sharedFileDAO = new SharedFileDAO();
            tx = HibernateSessionFactory.getSession().beginTransaction();
            SharedFile sharedFile = sharedFileDAO.findById(sharedFileId);
            boolean isRecommended = sharedFile.getIsRecommended();
            if(isRecommended)
                sharedFile.setIsRecommended(false);
            else
                sharedFile.setIsRecommended(true);
            sharedFileDAO.modify(sharedFile);
            tx.commit();
        }
        catch(Exception e)
        {
            if(tx != null)tx.rollback();
            //throw new QaException(e);
        }
        finally
        {
            HibernateSessionFactory.closeSession();  
        }
    }

    /**
     * if share file is open, set to hide
     * if share file is hide, set to open
     * @param sharedFileId
     * @param errors
     */
    private void hideOrOpen(int sharedFileId,ActionMessages errors)
    {
        Transaction tx = null;
        try
        {
            SharedFileDAO sharedFileDAO = new SharedFileDAO();
            tx = HibernateSessionFactory.getSession().beginTransaction();
            SharedFile sharedFile = sharedFileDAO.findById(sharedFileId);
            String state = sharedFile.getState();
            if("0".equals(state))
                sharedFile.setState("1");
            else
                sharedFile.setState("0");
            sharedFileDAO.modify(sharedFile);
            tx.commit();
        }
        catch(Exception e)
        {
            if(tx != null)tx.rollback();
            //throw new QaException(e);
        }
        finally
        {
            HibernateSessionFactory.closeSession();  
        }
    }

    //if file is not null, delete original file and add new

    private void modify(ShareFileForm shareFileForm, Integer userId,ActionMessages errors) throws QaException
    {
        Transaction tx = null;
        boolean needRollback = true;        
        try
        {
            String newFilePath = "";
            //new file
            FormFile file = shareFileForm.getFile();
            boolean ifUploadNewFile = false;
            String ext = "";
            SharedFileDAO sharedFileDAO = new SharedFileDAO();
            tx = HibernateSessionFactory.getSession().beginTransaction();
            SharedFile sharedFile = sharedFileDAO.findById(shareFileForm.getId());
            if(file != null && file.getFileSize() > 0)
            {
                ifUploadNewFile = true;
                String sharedFileDirStr = getPhisicalSharedFileDir();
                String oldFilePath = sharedFileDirStr+sharedFile.getPath();
                try
                {
                    File oldFile = new File(oldFilePath);
                    if(oldFile.exists())
                        oldFile.delete();
                }
                catch(Exception e)
                {
                    log.error("delete share file "+oldFilePath+" exception:"+e);
                }

                ifUploadNewFile = true;
                String fName = file.getFileName();
                if(checkIfFileExist(fName))
                {
                    errors.add("",new ActionMessage("sharedfile.exist",fName));
                    needRollback = false;
                    throw new QaException("File can not be overwrite");
                }
                ext = fName.substring(fName.lastIndexOf(".")+1);
                try
                {
                    InputStream in = file.getInputStream();
                    String yearMonthDayPath = checkAndBuildYearMonthDayDir();// /yyyy/mm/dd
                    String dirPath = getPhisicalSharedFileDir()+yearMonthDayPath;// /root/sharedfile/yyyy/mm/dd
                    String phisicalFile = "";
                    phisicalFile = dirPath+fileSeparator+fName;
                    newFilePath = yearMonthDayPath+fileSeparator+fName;// /yyyy/mm/dd/file.ext
                    OutputStream out = new FileOutputStream(phisicalFile);
                    Util.copyStream(in, out);
                    in.close();
                    out.close();
                }
                catch(Exception e)
                {
                    errors.add("",new ActionMessage("uploadfile.failure",fName));
                    log.error("add share file into dir exception:"+e);
                    throw e;
                }
                String name = shareFileForm.getName();
                sharedFile.setName(name);
                sharedFile.setPath(newFilePath);
                sharedFile.setSize(file.getFileSize());
                sharedFile.setFileType(ext);
            }
            else
            {
                String name = shareFileForm.getName();
                sharedFile.setName(name);
            }
            sharedFile.setDescription(shareFileForm.getDescription());
            sharedFile.setChangeDate(new Date());
            sharedFileDAO.modify(sharedFile);
            tx.commit();
        }
        catch(QaException qe)
        {
            log.error("modify share file object exception:"+qe);
        }
        catch(Exception e)
        {
            if(tx != null && needRollback)tx.rollback();
        }
        finally
        {
            HibernateSessionFactory.closeSession();  
        }
    }        

    //if file is not null, delete original file and add new

    private void modifyBack(ShareFileForm shareFileForm, Integer userId,ActionMessages errors) throws QaException
    {
        Transaction tx = null;
        try
        {
            SharedFileDAO sharedFileDAO = new SharedFileDAO();
            tx = HibernateSessionFactory.getSession().beginTransaction();
            SharedFile sharedFile = sharedFileDAO.findById(shareFileForm.getId());
            //new file
            FormFile file = shareFileForm.getFile();
            String name = shareFileForm.getName();            
            sharedFile.setName(name);
            log.info("name.length="+name.length());
            boolean ifUploadNewFile = false;
            String ext = "";
            if(file != null && file.getFileSize() > 0)
            {
                ifUploadNewFile = true;
                String fName = file.getFileName();
                ext = fName.substring(fName.lastIndexOf(".")+1);
                String phisicalFilePath = makePhisicalFilePath(userId,shareFileForm.getId());
                sharedFile.setPath(phisicalFilePath+name+"."+ext);
                sharedFile.setSize(file.getFileSize());
                sharedFile.setFileType(ext);
            }            
            Date date = new Date();
            sharedFile.setDescription(shareFileForm.getDescription());
            sharedFile.setChangeDate(date);            
            sharedFileDAO.modify(sharedFile);
            if(ifUploadNewFile)
            {
                try
                {
                    String sharedFileDirStr = GlobalConfigs.WEB_PHISICAL_ROOT_LOCATION+GlobalConfigs.SHAREDFILE_DIR;
                    //delete old file
                    String oldFilePath = sharedFile.getPath();
                    if(oldFilePath != null && oldFilePath.length() > 0)
                    {
                        String oldPhisicalFilePath = sharedFileDirStr+oldFilePath;
                        log.info("old phisicalFile="+oldPhisicalFilePath);
                        File oldPhisicalFile = new File(oldPhisicalFilePath);
                        oldPhisicalFile.delete();
                    }
                    InputStream in = file.getInputStream();
                    //WEB_PHISICAL_ROOT_LOCATION /*/
                    File sharedFileDir = new File(sharedFileDirStr);
                    if(!sharedFileDir.exists())
                    {
                        sharedFileDir.mkdir();
                    }
                    //userId
                    String userDirStr = sharedFileDirStr+fileSeparator+userId;
                    File userDir = new File(userDirStr);
                    if(!userDir.exists())
                    {
                        userDir.mkdir();
                    }
                    String datetimeDirStr = userDirStr+fileSeparator+getDateTimeString(shareFileForm.getId());
                    File datetimeDir = new File(datetimeDirStr);
                    if(!datetimeDir.exists())
                    {
                        datetimeDir.mkdir();
                    }
                    String phisicalFile = datetimeDirStr+fileSeparator+name+"."+ext;
                    log.info("phisicalFile="+phisicalFile);
                    OutputStream out = new FileOutputStream(phisicalFile);
                    Util.copyStream(in, out);
                    in.close();
                    out.close();
                }
                catch(Exception e)
                {
                    errors.add("",new ActionMessage("uploadfile.failure",name));
                    log.error("modify shared file e="+e);
                    throw e;
                }
            }            
            
            /*
            if(fName.length() > 0)
            {
                InputStream in = file.getInputStream();
                Blob fileContent = Hibernate.createBlob(in);
                UploadedFile uf = new UploadedFile();
                uf.setId("sf"+sharedFile.getId());
                uf.setContent(fileContent);
                uf.setName(shareFileForm.getName());
                UploadedFileDAO ufDAO = new UploadedFileDAO();
                ufDAO.save(uf);
            }*/
            tx.commit();
        }
        catch(Exception e)
        {
            if(tx != null)tx.rollback();
        }
        finally
        {
            HibernateSessionFactory.closeSession();  
        }
    }        

    /*
     *Below are private methods
     */
    private List search(int page,int pageSize,String searchText) throws QaException
    {
        Transaction tx = null;
        try
        {
            SharedFileDAO sharedFileDAO = new SharedFileDAO();
            sharedFileDAO.setPage(page, pageSize);
            tx = HibernateSessionFactory.getSession().beginTransaction();
            List list = null;
            list = sharedFileDAO.search(searchText);
            tx.commit();
            return list;
        }
        catch(Exception e)
        {
            throw new QaException(e);
        }
        finally
        {
            HibernateSessionFactory.closeSession();
        }
    }

    private int countSearch(String searchText) throws QaException
    {    
        Transaction tx = null;
        int count = 0;
        try
        {
            SharedFileDAO sharedFileDAO = new SharedFileDAO();
            tx = HibernateSessionFactory.getSession().beginTransaction();
            count = sharedFileDAO.countSearch(searchText);
            tx.commit();
        }
        catch(Exception e)
        {
            throw new QaException(e);
        }
        finally
        {
            HibernateSessionFactory.closeSession();
        }
        return count;
    }    

    
    /*
     *Below are private methods
     */
    private List list(int page,int pageSize,Integer catId,HttpServletRequest request) throws QaException
    {
        Transaction tx = null;
        try
        {
            SharedFileDAO sharedFileDAO = new SharedFileDAO();
            sharedFileDAO.setPage(page, pageSize);
            tx = HibernateSessionFactory.getSession().beginTransaction();
            List list = null;
            if(catId != null)
            {
                SharedFileCategoryDAO sharedFileCategoryDAO = new SharedFileCategoryDAO();
                SharedFileCategory sfc = sharedFileCategoryDAO.findById(catId);
                request.setAttribute("sfc",sfc);
                list = sharedFileDAO.findAllSharedFilesUnderSharedFileCategory(sfc);
            }
            else
            {
                list = sharedFileDAO.findSharedFiles();
            }
            tx.commit();
            return list;
        }
        catch(Exception e)
        {
            if(tx != null)tx.rollback();
            throw new QaException(e);
        }
        finally
        {
            HibernateSessionFactory.closeSession();
        }
    }
        
    private int countSharedFile(Integer catId) throws QaException
    {    
        Transaction tx = null;
        int count = 0;
        try
        {
            SharedFileDAO sharedFileDAO = new SharedFileDAO();
            SharedFileCategoryDAO sharedFileCategoryDAO = new SharedFileCategoryDAO();
            tx = HibernateSessionFactory.getSession().beginTransaction();
            if(catId != null)
            {
                SharedFileCategory sfc = sharedFileCategoryDAO.findById(catId);
                count = sharedFileDAO.countAllSharedFilesUnderSharedFileCategory(sfc);
            }
            else
            {
                count = sharedFileDAO.countSharedFiles();
            }
            tx.commit();
        }
        catch(Exception e)
        {
            if(tx != null)tx.rollback();
            throw new QaException(e);
        }
        finally
        {
            HibernateSessionFactory.closeSession();
        }
        return count;
    }    



    /*
     *Below are private methods
     */
    private List recommendedList(int page,int pageSize,Integer catId,HttpServletRequest request) throws QaException
    {
        Transaction tx = null;
        try
        {
            SharedFileDAO sharedFileDAO = new SharedFileDAO();
            sharedFileDAO.setPage(page, pageSize);
            tx = HibernateSessionFactory.getSession().beginTransaction();
            List list = null;
            if(catId != null)
            {
                SharedFileCategoryDAO sharedFileCategoryDAO = new SharedFileCategoryDAO();
                SharedFileCategory sfc = sharedFileCategoryDAO.findById(catId);
                request.setAttribute("sfc",sfc);
                list = sharedFileDAO.findAllRecommendedSharedFilesUnderSharedFileCategory(sfc);
            }
            else
            {
                list = sharedFileDAO.findAllRecommendedSharedFiles();
            }
            tx.commit();
            return list;
        }
        catch(Exception e)
        {
            if(tx != null)tx.rollback();
            throw new QaException(e);
        }
        finally
        {
            HibernateSessionFactory.closeSession();
        }
    }

    private int countRecommendedSharedFile(Integer catId) throws QaException
    {    
        Transaction tx = null;
        int count = 0;
        try
        {
            SharedFileDAO sharedFileDAO = new SharedFileDAO();
            SharedFileCategoryDAO sharedFileCategoryDAO = new SharedFileCategoryDAO();
            tx = HibernateSessionFactory.getSession().beginTransaction();
            if(catId != null)
            {
                SharedFileCategory sfc = sharedFileCategoryDAO.findById(catId);
                count = sharedFileDAO.countAllRecommendedSharedFilesUnderSharedFileCategory(sfc);
            }
            else
            {
                count = sharedFileDAO.countAllRecommendedSharedFiles();
            }
            tx.commit();
        }
        catch(Exception e)
        {
            if(tx != null)tx.rollback();
            throw new QaException(e);
        }
        finally
        {
            HibernateSessionFactory.closeSession();
        }
        return count;
    }    

    public SharedFile view(Integer id) throws QaException
    {
        Transaction tx = null;
        try
        {
            SharedFileDAO sharedFileDAO = new SharedFileDAO();
            tx = HibernateSessionFactory.getSession().beginTransaction();
            SharedFile sharedFile = sharedFileDAO.findById(id);
            sharedFile.setViewCount(sharedFile.getViewCount()+1);
            tx.commit();
            return sharedFile;
        }
        catch(Exception e)
        {
            if(tx != null)tx.rollback();
            throw new QaException(e);
        }
        finally
        {
            HibernateSessionFactory.closeSession();  
        }
    }
    //not count the click
    public SharedFile get(Integer id) throws QaException
    {
        Transaction tx = null;
        try
        {
            SharedFileDAO sharedFileDAO = new SharedFileDAO();
            tx = HibernateSessionFactory.getSession().beginTransaction();
            SharedFile sharedFile = sharedFileDAO.findById(id);
            tx.commit();
            return sharedFile;
        }
        catch(Exception e)
        {
            if(tx != null)tx.rollback();
            throw new QaException(e);
        }
        finally
        {
            HibernateSessionFactory.closeSession();  
        }
    }

    private int delete(Integer id,int userId,String userType,ActionMessages errors) throws QaException
    {
        SharedFileDAO sharedFileDAO = new SharedFileDAO();
        SharedFileCategoryDAO catDAO = new SharedFileCategoryDAO();
        String path = "";
        Transaction tx = null;
        int catId;
        try
        {
            tx = HibernateSessionFactory.getSession().beginTransaction();
            SharedFile sharedFile = sharedFileDAO.findById(id);
            SharedFileCategory cat = sharedFile.getMrIaskSharedFileCategory();
            catId = cat.getId();
            if(sharedFile.getMrIaskUser().getId() != userId)
            {
                if(!"1".equals(userType))
                {
                    errors.add("", new ActionMessage("Only Author can delete",false));
                    return -1;
                }
            }
            path = sharedFile.getPath();
            cat.setFileCount(cat.getFileCount()-1);
            sharedFileDAO.delete(sharedFile);
            catDAO.update(cat);
            /*int count = sharedFile.getDownloadCount();
            if(count != 0){
            	sharedFileDAO.addScoreHistory(sharedFile.getMrIaskUser(), id, sharedFile.getName(), UserScoreHistoryConstants.USER_SCORE_HISTORY_DELETE_SHARED_FILES, "delete shared files", 0-count);
            }*/
            sharedFileDAO.addScoreHistory(sharedFile.getMrIaskUser(), id, sharedFile.getName(), UserScoreHistoryConstants.USER_SCORE_HISTORY_DELETE_SHARED_FILES, "delete shared files");
            tx.commit();
            try
            {
                String sharedFileDirStr = GlobalConfigs.WEB_PHISICAL_ROOT_LOCATION+GlobalConfigs.SHAREDFILE_DIR;
                String phisicalFile = sharedFileDirStr+path;
                File file = new File(phisicalFile);
                if(file.exists())
                {
                    file.delete();
                }
                else
                {
                    log.info(phisicalFile+" does not exist");
                }
            }
            catch(Exception e)
            {
                log.error("delete share file exception:"+e);
            }
        }
        catch(Exception e)
        {
            if(tx != null)tx.rollback();
            log.error("delete share file object exception:"+e);
            throw new QaException(e);
        }
        finally
        {
            HibernateSessionFactory.closeSession();  
        }
        return catId;
    }           


    /**
      * retrive the size of unread messages of the user
      * @deprecated
      * @param request HttpServletRequest
      * @return
      * @throws QaException
     */
     private void saveUserMessageSizeAndUpdateUserScoreInSession1(HttpServletRequest request) throws QaException
     {
         int messageSize = 0;
         try
         {
             UserSession us = UserSessionUtil.getUserSession(request);
             if(us == null)return;
             Integer userId = us.getUserId();
             Transaction tx = HibernateSessionFactory.getSession().beginTransaction();
             UserDAO userDAO = new UserDAO();
             User user = userDAO.findById(userId);
             messageSize = user.getNewMessages().size();
             tx.commit();
             us.setLoginName(user.getLoginName());
             us.setScore(user.getUserScore().getTotalScore());
             request.getSession().setAttribute("messagesize",messageSize);
         }
         catch(Exception e)
         {
             //throw new QaException(e);
         }
         finally
         {
             HibernateSessionFactory.closeSession();
         }
     }



    /*
    public ActionForward doAction(ActionMapping mapping, ActionForm form,
    		HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        UserSession us = UserSessionUtil.getUserSession(request);
        String action = this.getAction(request);
        ShareFileForm shareFileForm = (ShareFileForm)form;
        Integer catId = shareFileForm.getCatId();
        //log.info("catId="+catId);
        Integer id = shareFileForm.getId();
        //log.info("id="+id);
        Integer page = shareFileForm.getPage();
        //log.info("page="+page);
        if(page == null || page == 0)
        {
            page = 1;
        }
        int pageSize = shareFileForm.getPageSize();
        if(pageSize == 0)
        {
            pageSize = 15;
        }
        //log.info("page1="+page);
        ActionForward af = null;
        if("list".equals(action))
        {
            int resultSize = countSharedFile(catId);
            request.setAttribute("resultSize",resultSize);
            //log.info("hre resultSize="+resultSize);
            request.setAttribute("sfs",list(page, pageSize,catId));
        }
        else if("premodify".equals(action))
        {
            request.setAttribute("sharedFile",view(id));
        }
        else if("add".equals(action))
        {
            add(shareFileForm,us.getUserId());
            String path = mapping.findForward(action).getPath();
            af = new ActionForward(path);
            af.setRedirect(true);
        }
        else if("delete".equals(action))
        {
            delete(id);
        }
        else if("premodify".equals(action))
        {
            request.setAttribute("sf",view(id));
        }
        else if("modify".equals(action))
        {
            modify(shareFileForm,us.getUserId());
        }
        else if("download".equals(action))
        {
            download(id);
            String path = mapping.findForward(action).getPath();
            path = path.replace("!?","sf"+id);
            af = new ActionForward(path);
            af.setRedirect(true);
        }
        if(af == null)
            return mapping.findForward(action);
        else
            return af;
    }
    
    
        
    private String download(Integer id) throws QaException
    {
        Transaction tx = null;
        try
        {
            SharedFileDAO sharedFileDAO = new SharedFileDAO();
            tx = HibernateSessionFactory.getSession().beginTransaction();
            SharedFile sharedFile = sharedFileDAO.findById(id);
            sharedFile.setDownloadCount(sharedFile.getDownloadCount()+1);
            sharedFileDAO.modify(sharedFile);
            tx.commit();
            return sharedFile.getPath();
        }
        catch(Exception e)
        {
            if(tx != null)tx.rollback();
            throw new QaException(e);
        }
        finally
        {
            HibernateSessionFactory.closeSession();  
        }
    }
        
    public SharedFile view(Integer id) throws QaException
    {
        Transaction tx = null;
        try
        {
            SharedFileDAO sharedFileDAO = new SharedFileDAO();
            tx = HibernateSessionFactory.getSession().beginTransaction();
            SharedFile sharedFile = sharedFileDAO.findById(id);
            tx.commit();
            return sharedFile;
        }
        catch(Exception e)
        {
            if(tx != null)tx.rollback();
            throw new QaException(e);
        }
        finally
        {
            HibernateSessionFactory.closeSession();  
        }
    }
        
    public List list(int page,int pageSize,Integer catId) throws QaException
    {
        Transaction tx = null;
        try
        {
            SharedFileDAO sharedFileDAO = new SharedFileDAO();
            SharedFileCategoryDAO sharedFileCategoryDAO = new SharedFileCategoryDAO();
            sharedFileDAO.setPage(page, pageSize);
            tx = HibernateSessionFactory.getSession().beginTransaction();
            List list = null;
            if(catId != null)
            {
                SharedFileCategory sfc = sharedFileCategoryDAO.findById(catId);
                list = sharedFileDAO.findAllSharedFilesUnderSharedFileCategory(sfc);
            }
            else
            {
                list = sharedFileDAO.findSharedFiles();
            }
            tx.commit();
            return list;
        }
        catch(Exception e)
        {
            if(tx != null)tx.rollback();
            throw new QaException(e);
        }
        finally
        {
            HibernateSessionFactory.closeSession();
        }
    }
	
    public int countSharedFile(Integer catId) throws QaException
    {    
        Transaction tx = null;
        int count = 0;
        try
        {
            SharedFileDAO sharedFileDAO = new SharedFileDAO();
            SharedFileCategoryDAO sharedFileCategoryDAO = new SharedFileCategoryDAO();
            tx = HibernateSessionFactory.getSession().beginTransaction();
            List list = null;
            if(catId != null)
            {
                SharedFileCategory sfc = sharedFileCategoryDAO.findById(catId);
                count = sharedFileDAO.countAllSharedFilesUnderSharedFileCategory(sfc);
            }
            else
            {
                count = sharedFileDAO.countSharedFiles();
            }
            tx.commit();
        }
        catch(Exception e)
        {
            if(tx != null)tx.rollback();
            throw new QaException(e);
        }
        finally
        {
            HibernateSessionFactory.closeSession();
        }
        return count;
    }    
    
    public List search(Integer page,String name) throws QaException
    {
        Transaction tx = null;
        try
        {
            SharedFileDAO sharedFileDAO = new SharedFileDAO();
            sharedFileDAO.setPage(page, new Integer(30));
            tx = HibernateSessionFactory.getSession().beginTransaction();
            List list = null;
            list = sharedFileDAO.findByName(name);
            tx.commit();
            return list;
        }
        catch(Exception e)
        {
            if(tx != null)tx.rollback();
            throw new QaException(e);
        }
        finally
        {
            HibernateSessionFactory.closeSession();  
        }
    }

    public void add(ShareFileForm shareFileForm, Integer userId) throws QaException
    {
        Transaction tx = null;
        try
        {
            SharedFileDAO sharedFileDAO = new SharedFileDAO();
            UserDAO userDAO = new UserDAO();
            SharedFileCategoryDAO sharedFileCategoryDAO = new SharedFileCategoryDAO();
            tx = HibernateSessionFactory.getSession().beginTransaction();
            User user = userDAO.findById(userId);
            SharedFileCategory sharedFileCategory = sharedFileCategoryDAO.findById(shareFileForm.getCatId());
            FormFile file = shareFileForm.getFile();
            String fName = file.getFileName();
            Date date = new Date();
            SharedFile sharedFile = new SharedFile();
            double random = Math.random();
            long curtime = date.getTime();
            if(fName.length() > 0)
            {
                String ext = fName.substring(fName.lastIndexOf("."));
                String path = curtime + "_" + userId + "_" + random + ext;
                sharedFile.setPath(path);
                sharedFile.setName(shareFileForm.getName());
                sharedFile.setSize(file.getFileSize());
            }
            sharedFile.setPostDate(date);
            sharedFile.setMrIaskUser(user);
            sharedFile.setMrIaskSharedFileCategory(sharedFileCategory);
            sharedFile.setDownloadCount(0);
            sharedFileDAO.save(sharedFile);
            if(fName.length() > 0)
            {
                InputStream in = file.getInputStream();
                Blob fileContent = Hibernate.createBlob(in);
                UploadedFile uf = new UploadedFile();
                uf.setId("sf"+sharedFile.getId());
                uf.setContent(fileContent);
                uf.setName(shareFileForm.getName());
                UploadedFileDAO ufDAO = new UploadedFileDAO();
                ufDAO.save(uf);
            }
            tx.commit();
        }
        catch(Exception e)
        {
            if(tx != null)tx.rollback();
            throw new QaException(e);
        }
        finally
        {
            HibernateSessionFactory.closeSession();  
        }
    }    

    public void modify(ShareFileForm shareFileForm,Integer userId) throws QaException
    {
        Transaction tx = null;
        try
        {
            SharedFileDAO sharedFileDAO = new SharedFileDAO();
            tx = HibernateSessionFactory.getSession().beginTransaction();
            SharedFile sharedFile = sharedFileDAO.findById(shareFileForm.getId());
            FormFile file = shareFileForm.getFile();
            String fName = file.getFileName();
            Date date = new Date();
            if(fName.length() > 0)
            {
                String ext = fName.substring(fName.lastIndexOf("."));
                String path = date.getTime() + "_" + userId + "_" + Math.random() + ext;
                sharedFile.setPath(path);
                sharedFile.setName(shareFileForm.getName());
            }
            sharedFile.setName(shareFileForm.getName());
            sharedFileDAO.modify(sharedFile);
            tx.commit();
        }
        catch(Exception e)
        {
            if(tx != null)tx.rollback();
            throw new QaException(e);
        }
        finally
        {
            HibernateSessionFactory.closeSession();  
        }
    }
	
    public void delete(Integer id) throws QaException
    {
        SharedFileDAO sharedFileDAO = new SharedFileDAO();
        String path = "";
        Transaction tx = null;
        try
        {
            tx = HibernateSessionFactory.getSession().beginTransaction();
            SharedFile sharedFile = sharedFileDAO.findById(id);
            path = sharedFile.getPath();
            sharedFileDAO.delete(sharedFile);
            tx.commit();
        }
        catch(Exception e)
        {
            if(tx != null)tx.rollback();
            throw new QaException(e);
        }
        finally
        {
            HibernateSessionFactory.closeSession();  
        }
    }*/           
     
     private void checkDownload(HttpServletRequest request){
    	 UserSession us = UserSessionUtil.getUserSession(request);
         UserDAO userDAO = new UserDAO();
         if(us == null){
        	 return;
         }
         User user = userDAO.findById(us.getUserId());
         
         if(user.getUserMoney().getTotalMoney().compareTo(GlobalConfigs.SHARED_FILE_MONEY) < 0){
        	 request.setAttribute("needMoney", GlobalConfigs.SHARED_FILE_MONEY);
        	 return;
         }
         
         Calendar cal = Calendar.getInstance();
         Date registerDate = user.getRegisterDate();
         Calendar registerCal = Calendar.getInstance();
         registerCal.setTime(registerDate);
         registerCal.add(Calendar.HOUR, GlobalConfigs.INTERVAL_REGISTER_DOWNLOAD);
         if(registerCal.after(cal)){
        	 request.setAttribute("registerInterval", GlobalConfigs.INTERVAL_REGISTER_DOWNLOAD);
        	 return;
         }
         
         DailyCheck dailyCheck = new DailyDownloadSharedFileCheck();
         dailyCheck.init(user.getId());
         boolean canAdd = dailyCheck.check(us.getUserId());
         if (!canAdd) {
        	 request.setAttribute("disableDownload", "true");
        	 return;
        }
     }
     
     private void checkCanAdd(ActionMapping mapping, HttpServletRequest request, ActionMessages errors) {
    	UserSession us = UserSessionUtil.getUserSession(request);
		DailyCheck dailyCheck = new DailyAddSharedFileCheck();
		dailyCheck.init(us.getUserId());
		long dif = (new Date().getTime() - us.getRegisterDate().getTime())/3600000;
        if( dif < GlobalConfigs.HOURS_ADDQUESTION_AFTER_REGISTRATION)
        {
            errors.add("addquestion-limit", new ActionMessage("sharedfile.add.limit.userregistration",
            ""+GlobalConfigs.HOURS_ADDQUESTION_AFTER_REGISTRATION));
			request.setAttribute("disableSubmit", "true");
			return;
        }
        if(!us.isActive()){
    		errors.add("addquestion-limit", new ActionMessage("user.inactive", ""));
    		request.setAttribute("disableSubmit", "true");
			return;
    	}
		boolean canAdd = dailyCheck.check(us.getUserId());
		if (!canAdd) {
			errors.add("addquestion-limit", new ActionMessage(
					"sharedfile.add.limit.dailynumber", ""
							+ GlobalConfigs.NUMBER_SHARED_FILE_A_USER_ONE_DAY));
			request.setAttribute("disableSubmit", "true");
		}
	}
}
